import time
from django import forms
from BloodSpiderModel.DjangoResponseTool import response_dict
from BloodSpiderAPI import models
from BloodSpiderAPI.apis.account.utils import utils_model_to_dict, is_valid_id_card
from django.db.models import Q



# 账号模型表单
class AccountForm(forms.ModelForm):
    class Meta:
        model = models.Account
        fields = ['username', 'password', 'phone', 'create_by']


# 创建账号
def create_account(request):
    if request.method == 'POST':
        try:
            # 复制 request.POST 的内容
            post_data = request.POST.copy()
            # 把user_id转换为用户对象
            post_data['create_by'] = request.user
            form = AccountForm(post_data)
            if form.is_valid():
                account = form.save()
                account_data = utils_model_to_dict(account)
                return response_dict.response_dict(message="账号创建成功", data=account_data)
            else:
                err = response_dict.get_first_error(form)
                return response_dict.response_dict(data=err, message=err[next(iter(err))] , code=1)
        except Exception as e:
            return response_dict.response_dict(data=str(e), code=1, message="创建账号失败")


# 分配账号API：开发将账号指定给当前所属人的功能
def assign_account(request):
    if request.method == 'POST':
        try:
            account_id = request.POST.get('account_id')
            owner_id = request.POST.get('owner_id')
            account = models.Account.objects.get(account_id=account_id)
            owner = models.User.objects.get(user_id=owner_id)
            account.current_owner = owner
            account.save()
            return response_dict.response_dict(message="账号分配成功", data=utils_model_to_dict(account))
        except Exception as e:
            return response_dict.response_dict(data=str(e), code=1, message="分配账号失败")


#  查询全部账号API：实现获取系统中所有账号信息的功能，支持分页处理
def get_all_accounts(request):
    # 如果是管理员,返回全部的账号,如果是运维,返回当前所需的账号
    if request.method == 'GET':
        try:
            page = int(request.GET.get('page', 1))
            page_size = int(request.GET.get('page_size', 10))
            # 状态 - 已分配或者未分配
            status = request.GET.get('status', '')
            if status == 'assigned':
                # 已分配账号
                account_query = models.Account.objects.filter(current_owner__isnull=False).order_by('-create_time')
            elif status == 'unassigned':
                # 未分配账号
                account_query = models.Account.objects.filter(current_owner__isnull=True).order_by('-create_time')
            else:
                account_query = models.Account.objects.filter(current_owner=request.user).order_by('-create_time')
            accounts = response_dict.get_page(account_query, page_size, page)
            account_list = [utils_model_to_dict(account) for account in accounts["page"]["object_list"]]
            del accounts["page"]["object_list"]
            return response_dict.response_dict(message="查询成功", data=account_list)
        except Exception as e:
            return response_dict.response_dict(data=str(e), code=1, message="查询账号失败")

# 搜索账号API：开发支持模糊搜索的功能，具体支持按名字和手机号和账号ID进行模糊匹配查询
def search_accounts(request):
    if request.method == 'GET':
        try:
            keyword = request.GET.get('keyword', '')
            # 状态 - 已分配或者未分配
            status = request.GET.get('status', '')
            # 构建查询条件
            query = Q()
            search_fields = Q(username__contains=keyword) | Q(phone__contains=keyword) | Q(account_id__contains=keyword)
            query &= search_fields
            if status == 'assigned':
                # 已分配账号
                query &= Q(current_owner__isnull=False)
            elif status == 'unassigned':
                # 未分配账号
                query &= Q(current_owner__isnull=True)
            # 执行查询
            accounts = models.Account.objects.filter(query)
            account_list = [utils_model_to_dict(account) for account in accounts]
            return response_dict.response_dict(message="查询成功", data=account_list)
        except Exception as e:
            return response_dict.response_dict(data=str(e), code=1, message="查询账号失败")

# 更新账号信息API：实现账号信息的部分更新功能，支持仅按传入的字段进行更新，保留未传入字段的原有值
def update_account(request):
    if request.method == 'POST':
        try:
            account_id = request.POST.get('account_id')
            if not account_id:
                return response_dict.response_dict(message="账号ID不能为空", code=1)
            # 查找要更新的账号
            account = models.Account.objects.get(account_id=account_id)
            # 判断是否是所属人或者是当前的运维人
            if account.create_by != request.user:
                if account.current_owner != request.user:
                    return response_dict.response_dict(message="您没有权限更新此账号", code=1)
            
            # 获取POST数据
            post_data = request.POST.copy()
            
            # 定义允许更新的字段列表
            allowed_fields = ['username', 'password', 'phone', 'balance', 'current_owner', 'delete_owner']
            
            # 构建更新数据字典
            update_data = {}
            
            # 参数验证
            for field in allowed_fields:
                if field in post_data:
                    value = post_data[field]
                    
                    # 特殊处理：如果密码为空字符串，则不更新密码
                    if field == 'password':
                        if value == '':
                            continue
                        # 密码长度验证
                        if len(value) < 6:
                            return response_dict.response_dict(message="密码长度不能少于6位", code=1)
                    elif field == 'delete_owner':
                        if value == 'true':
                            account.current_owner = None
                    # 用户名验证
                    elif field == 'username':
                        if not value or value.strip() == '':
                            return response_dict.response_dict(message="用户名不能为空", code=1)
                        # 检查用户名是否已被使用
                        if models.Account.objects.filter(username=value).exclude(account_id=account_id).exists():
                            return response_dict.response_dict(message="用户名已存在", code=1)
                            
                    # 手机号验证
                    elif field == 'phone':
                        if value and not value.isdigit():
                            return response_dict.response_dict(message="手机号只能包含数字", code=1)
                            
                    # 余额验证
                    elif field == 'balance':
                        try:
                            # 转换为浮点数并验证
                            balance_value = float(value)
                            if balance_value < 0:
                                return response_dict.response_dict(message="余额不能为负数", code=1)
                            update_data[field] = balance_value
                            continue  # 跳过下面的默认赋值
                        except ValueError:
                            return response_dict.response_dict(message="余额必须为数字", code=1)
                            
                    # 处理当前所有者
                    elif field == 'current_owner':
                        if value:
                            try:
                                owner = models.User.objects.get(user_id=value)
                                update_data[field] = owner
                            except models.User.DoesNotExist:
                                return response_dict.response_dict(message="指定的所有者不存在", code=1)
                        else:
                            update_data[field] = None
                            continue  # 跳过下面的默认赋值
                    
                    update_data[field] = value
            
            # 如果没有需要更新的字段
            if not update_data:
                return response_dict.response_dict(
                    message="没有提供需要更新的字段或提供的字段值无效",
                    code=1
                )
            
            # 执行更新
            for field, value in update_data.items():
                setattr(account, field, value)
            account.save()
            
            # 获取更新后的账号信息
            updated_account = utils_model_to_dict(account)
            
            return response_dict.response_dict(
                message="账号信息更新成功",
                data=updated_account
            )
        except models.Account.DoesNotExist:
            return response_dict.response_dict(message="账号不存在", code=1)
        except Exception as e:
            # 记录详细错误信息
            print(f"更新账号信息时发生错误: {str(e)}")
            return response_dict.response_dict(data=str(e), code=1, message="更新账号信息失败，请联系管理员")
    else:
        return response_dict.response_dict(message="请求方法错误，请使用POST方法", code=1)


# 注册平台
def register_platform(request):
    if request.method != 'POST':
        return response_dict.response_dict(message="请求方法错误，请使用POST方法", code=1)


    try:
        platform = models.Platform.objects.filter(platform_id=request.POST.get('platform_id')).first()
    
        account = models.Account.objects.filter(account_id=request.POST.get('account_id')).first()
        if not platform or not account:
            return response_dict.response_dict(message="平台或账号不存在", code=1)

        # 检查账号是否已注册该平台
        if platform in account.platform.all():
            return response_dict.response_dict(message="账号已注册该平台", code=1)
        
        # 注册平台
        account.platform.add(platform)
        account.save()
        
        return response_dict.response_dict(message="平台注册成功", code=0, data=utils_model_to_dict(account, show_platforms=True))
    except Exception as e:
        # 记录详细错误信息
        print(f"注册平台时发生错误: {str(e)}")
        return response_dict.response_dict(data=str(e), code=1, message="注册平台失败，请联系管理员")



# 获取注册的全部平台
def get_registered_platforms(request):
    if request.method != 'GET':
        return response_dict.response_dict(message="请求方法错误，请使用GET方法", code=1)
    
    account_id = request.GET.get('account_id')
    if not account_id:
        return response_dict.response_dict(message="缺少account_id参数", code=1)
    
    account = models.Account.objects.filter(account_id=account_id).first()
    if not account:
        return response_dict.response_dict(message="账号不存在", code=1)
    
    
    return response_dict.response_dict(
        message="获取注册平台成功",
        code=0,
        data=utils_model_to_dict(account, show_platforms=True)
    )


# 更新平台认证状态
def update_platform_real_name(request):
    return response_dict.response_dict(message="该接口已暂停使用", code=1)
    if request.method != 'POST':
        return response_dict.response_dict(message="请求方法错误，请使用POST方法", code=1)
    try:
        account_id = request.POST.get('account_id')
        platform_id = request.POST.get('platform_id')
        is_real_name = request.POST.get('is_real_name', "false")
        
        if not account_id or not platform_id or not is_real_name:
            return response_dict.response_dict(message="缺少必要参数", code=1)
        
        account = models.Account.objects.filter(account_id=account_id).first()
        platform = models.Platform.objects.filter(platform_id=platform_id).first()
        if not account or not platform:
            return response_dict.response_dict(message="账号或平台不存在", code=1)
        if is_real_name == "true":
            models.Platform_Account.objects.filter(platform=platform, account=account).update(is_real_name=True)
        elif is_real_name == "false":
            models.Platform_Account.objects.filter(platform=platform, account=account).update(is_real_name=False)
        else:
            return response_dict.response_dict(message="is_real_name参数错误，必须为'true'或'false'", code=1)

        
        return response_dict.response_dict(
            message="更新平台认证状态成功",
            code=0,
        )
    except Exception as e:
        # 记录详细错误信息
        print(f"更新平台认证状态时发生错误: {str(e)}")
        return response_dict.response_dict(data=str(e), code=1, message="更新平台认证状态失败，请联系管理员")


# 更新实名· 姓名和身份证号
def update_real_name(request):
    if request.method != 'POST':
        return response_dict.response_dict(message="请求方法错误，请使用POST方法", code=1)
    try:
        time.sleep(1)
        account_id = request.POST.get('account_id')
        # 平台id
        platform_id = request.POST.get('platform_id')
        real_name = request.POST.get('real_name')
        id_card = request.POST.get('id_card')
        
        if not account_id or not platform_id or not real_name or not id_card:
            return response_dict.response_dict(message="缺少必要参数", code=1)
        elif not is_valid_id_card(id_card):
            return response_dict.response_dict(message="身份证号格式错误", code=1)
        
        account = models.Platform_Account.objects.filter(account_id=account_id, platform_id=platform_id).first()
        id_card_exists = models.Platform_Account.objects.filter(platform_id=platform_id, id_card=id_card)
        if not account:
            return response_dict.response_dict(message="账号不存在", code=1)
        elif account.is_real_name:
            return response_dict.response_dict(message="账号已实名，无需重复操作", code=1)
        elif account.account.create_by != request.user and account.account.current_owner != request.user:
            return response_dict.response_dict(message="您没有权限操作该账号", code=1)
        elif id_card_exists.exists():
            return response_dict.response_dict(message=f"该身份证号已被{id_card_exists.first().account.username}使用", code=1)
        
        
        account.real_name = real_name
        account.id_card = id_card
        account.is_real_name = True
        account.save()
        
        return response_dict.response_dict(
            message="更新实名成功",
            code=0,
        )
    except Exception as e:
        # 记录详细错误信息
        print(f"更新实名时发生错误: {str(e)}")
        return response_dict.response_dict(data=str(e), code=1, message="更新实名失败，请联系管理员")


# 更新账号平台的运营状态
def update_platform_status(request):
    if request.method != 'POST':
        return response_dict.response_dict(message="请求方法错误，请使用POST方法", code=1)
    try:
        account_id = request.POST.get('account_id')
        platform_id = request.POST.get('platform_id')
        status_code = int(request.POST.get('status_code')) # 1正常, 2封号
        
        if not account_id or not platform_id or not status_code:
            return response_dict.response_dict(message="缺少必要参数", code=1)
        account = models.Platform_Account.objects.filter(account_id=account_id, platform_id=platform_id).first()
        if not account:
            return response_dict.response_dict(message="账号不存在", code=1)
        elif status_code not in [1, 2]:
            return response_dict.response_dict(message="status_code参数错误，必须为1或2", code=1)
        elif account.account.create_by != request.user and account.account.current_owner != request.user:
            return response_dict.response_dict(message="您没有权限操作该账号", code=1)
        
        account.status = status_code
        account.save()
        
        return response_dict.response_dict(
            message="更新平台运营状态成功",
            code=0,
        )
    except Exception as e:
        # 记录详细错误信息
        print(f"更新平台运营状态时发生错误: {str(e)}")
        return response_dict.response_dict(data=str(e), code=1, message="更新平台运营状态失败，请联系管理员")